<template>
  <Modal v-model="boxShow" :mask-closable="false" :title="boxTitle" :width="width" transfer @on-cancel="onCancel">
    <div v-if="boxShow">
      <PagingTable
        ref="helpBoxTable"
        :columns="tableColumnsClone"
        :dataUrl="tableUrl"
        :searchParams="searchParams"
        :page-size="pageSize"
        :showTableOption="false"
        :show-table-selection-bar="false"
        :transformResponse="transformResponse"
        size="small"
        @on-row-click="onRowClick"
        @on-selection-change="onSelectionChange"
        @on-select="onSelect"
        @on-select-cancel="onSelectCancel"
        @on-select-all="onSelectAll"
        @on-select-all-cancel="onSelectAllCancel">
        <slot slot="search" name="search-extend">
          <Input v-model="searchText" maxlength="50" :placeholder="placeholder" style="width: 200px"/>
          <Button icon="ios-search" style="margin-left:10px;" type="primary" @click="doSearch">查询</Button>
          <div v-if="rowName" class="tags">
            <Tag v-for="item in selectTags" :key="item.key" :name="item.key" closable @on-close="tagClose" color="primary">
              {{ item.value }}
            </Tag>
          </div>
        </slot>
      </PagingTable>
    </div>
    <div slot="footer">
      <Button ghost type="primary" @click="onClear">{{ clearText }}</Button>
      <Button type="primary" @click="onOk">确定</Button>
    </div>
  </Modal>
</template>

<script>
import PagingTable from '@/components/paging-table/index'
import { deepCopy } from '@/libs/tools'

export default {
  name: 'helpbox',
  components: {
    PagingTable
  },
  props: {
    value: Boolean,
    url: String,
    columns: Array,
    title: {
      type: String,
      default: '帮助框'
    },
    width: {
      type: Number,
      default: 520
    },
    multiSelect: {
      type: Boolean,
      default: false
    },
    // 外部查询条件
    helpBoxSearchParams: {
      type: Object,
      default: () => {}
    },
    clearText: {
      type: String,
      require: false,
      default: '清空'
    },
    // Tag显示时的key，建议为唯一id
    rowKey: {
      type: String,
      require: false,
      default: ''
    },
    // Tag显示时的value
    rowName: {
      type: String,
      require: false,
      default: ''
    },
    // 父组件回填已选中的值
    selectedKey: {
      type: Array,
      require: false,
      default: ()=> []
    },
    pageSize: {
      type: Number,
      default: 10
    },
    placeholder: {
      type: String,
      default: '搜索'
    }
  },
  data () {
    return {
      boxShow: this.value,
      searchText: '',
      reSetPages: false,
      selectStore: [],
      selectTags: [],
      selectRows: [],
      selectedKeys: [],
      searchParams: {},
      tableColumnsClone: [],
      timer: {}
    }
  },
  computed: {
    tableUrl: function () {
      return this.url
    },
    boxTitle: function () {
      return this.title
    }
  },
  methods: {
    init: function () {
      let self = this
      self.selectStore = []
      let selectColumn = {
        width: 80,
        align: 'center',
        title: '选择'
      }
      if (this.multiSelect) {
        selectColumn.type = 'selection'
      } else {
        selectColumn.type = 'single-selection'
      }
      this.tableColumnsClone = deepCopy(this.columns)
      this.tableColumnsClone.unshift(selectColumn)
      this.searchParams = Object.assign({}, {
        search: self.searchText
      }, self.helpBoxSearchParams)
    },
    onOk: function () {
      let result = null
      if (this.multiSelect && this.rowKey) {
        let selectStore = []
        for (let item in this.selectRows) {
          selectStore.push(this.selectRows[item])
        }
        result = selectStore
        this.selectStore = selectStore
      }
      if (this.selectStore.length > 0) {
        if (this.multiSelect) {
          result = this.selectStore
        } else {
          result = this.selectStore[0]
        }
        this.$emit('onOk', result)
        this.$emit('input', false)
        this.clearSelectData()
        this.boxShow = false
      } else {
        this.$Message.error('请选择一条记录')
      }
    },
    onClear: function () {
      this.clearSelectData()
      this.$emit('onClear')
      this.$emit('input', false)
      this.boxShow = false
    },
    onCancel: function () {
      // 改为：点击右上角的X时，不再清空数据
      // this.clearSelectData()
      this.$emit('input', false)
      this.boxShow = false
    },
    doSearch: function () {
      // this.clearSelectData();
      this.searchParams = Object.assign({}, {
        search: this.searchText
      }, this.helpBoxSearchParams)
    },
    onRowClick: function (row, index) {
      this.selectOnChange(row, index)
    },
    // 单选
    selectOnChange: function (row, index) {
      this.selectStore = [row]
    },
    // 多选
    onSelectionChange: function (rows) {
      if (!this.rowKey) {
        this.selectStore = rows
      } else {
        this.selectStore = rows
        if (rows && rows.length > 0) {
          for (let i = 0; i < rows.length; i++) {
            let row = rows[i]
            if (!this.selectTags.some(item => item.key === row[this.rowKey])) {
              let tagItem = { 'key': row[this.rowKey], 'value': row[this.rowName] }
              this.selectTags.push(tagItem)
            }
          }
        }
      }
    },
    onSelect: function (selection, row) {
      if (this.rowKey) {
        this.selectRows[row[this.rowKey]] = row
      }
    },
    onSelectCancel: function (selection, row) {
      if (this.rowKey) {
        delete this.selectRows[row[this.rowKey]]
        const selectIndex = (this.selectTags || []).findIndex((selectItem) => selectItem.key === row[this.rowKey])
        if (selectIndex > -1) {
          this.selectTags.splice(selectIndex, 1)
        }
      }
    },
    onSelectAll: function (selection) {
      if (this.rowKey) {
        for (let item of selection) {
          this.selectRows[item[this.rowKey]] = item
        }
      }
    },
    onSelectAllCancel: function () {
      if (this.rowKey) {
        let currentTableData = this.$refs.helpBoxTable.$data.tableData
        for (let i = 0; i < currentTableData.length; i++) {
          let tempData = currentTableData[i][this.rowKey]
          delete this.selectRows[tempData]
          const selectIndex = (this.selectTags || []).findIndex((selectItem) => selectItem.key === tempData)
          if (selectIndex > -1) {
            this.selectTags.splice(selectIndex, 1)
          }
        }
      }
    },
    transformResponse: function (resp) {
      if (this.rowKey) {
        if (resp.code === 200) {
          let tableData = resp.data.rows
          for (let i = 0, len = tableData.length; i < len; i++) {
            if (this.selectRows[tableData[i][this.rowKey]]) {
              tableData[i]._checked = true
            }
          }
          resp.data.rows = tableData
        }
      }
      return resp
    },
    clearSelectData: function () {
      this.selectStore = []// 清空已选数据
      this.selectRows = []// 清空已选数据
      this.selectTags = []// 清空所选标签
      this.selectedKeys = []// 清空默认选择
    },
    tagClose: function (event, name) {
      const selectIndex = (this.selectTags || []).findIndex((selectItem) => selectItem.key === name)
      const dataIndex = (this.$refs.helpBoxTable.$data.tableData || []).findIndex((selectItem) => selectItem[this.rowKey] === name)
      if (selectIndex > -1) {
        this.selectTags.splice(selectIndex, 1)
        this.selectStore.splice(selectIndex, 1)
      }
      delete this.selectRows[name]
      if (dataIndex > -1) {
        this.$refs.helpBoxTable.$refs.tableRef.toggleSelect(dataIndex)
      }
    }
  },
  watch: {
    value: function () {
      if (this.value) {
        this.boxShow = true
      }
      this.searchText = ''
      this.searchParams = Object.assign({}, {
        search: this.searchText
      }, this.helpBoxSearchParams)
    },
    multiSelect: function () {
      this.init()
    },
    columns: function () {
      this.init()
    },
    helpBoxSearchParams: function () {
      this.init()
    },
    // 去掉searchText的监听，客户想查询自己点查询按钮
    // searchText: function () {
    //   let self = this
    //   clearTimeout(self.timer)
    //   self.timer = setTimeout(() => {
    //     self.searchParams = Object.assign({}, {
    //       search: self.searchText
    //     }, self.helpBoxSearchParams)
    //   }, 750)
    // },
    selectedKey: function () {
      this.selectedKeys = this.selectedKey
      if (this.rowKey) {
        for (let item of this.selectedKeys) {
          this.selectRows[item[this.rowKey]] = item
          let tagItem = { 'key': item[this.rowKey], 'value': item[this.rowName] }
          this.selectTags.push(tagItem)
        }
      }
      this.init()
    }
  },
  created () {
    this.init()
  }
}
</script>

<style scoped>
.tags {
  margin: 10px auto;
}
</style>
